#!/usr/bin/python
# -*- coding: UTF-8 -*-
from  datetime  import  * 
import pymysql, sys, urllib.request, json, time, uuid

url = 'http://apis.baidu.com/apistore/currencyservice/type'
apikey = '95fe6ae8a7c0030173ee16d93ea01855'
m_host = 'rm-2ze2us2r61990270t.mysql.rds.aliyuncs.com'
m_user = 'shsytour'
m_passwd = '123456'
m_db = 'shsytour'
m_charset = 'utf8'

def getCurrency(hbs):
	conn = pymysql.connect(host=m_host,user=m_user,passwd=m_passwd,db=m_db,charset=m_charset);
	cur = conn.cursor()
	i = 1
	for hb in hbs:
		url = 'http://apis.baidu.com/apistore/currencyservice/currency?fromCurrency=CNY&toCurrency='+hb+'&amount=1'
		print(url)
		req = urllib.request.Request(url)

		req.add_header("apikey", apikey)

		resp = urllib.request.urlopen(req)
		contentc = resp.read()
		if(contentc):
			a = json.loads(bytes.decode(contentc))
			if a['errMsg'] == 'success':
				print(i)
				i = i+1
				uid = str(uuid.uuid4())
				fromCurrency = a['retData']['fromCurrency']
				toCurrency = a['retData']['toCurrency']
				dates = a['retData']['date']
				times = a['retData']['time']
				currency = a['retData']['currency']
				created_at = str(datetime.fromtimestamp(time.time()))
				cur.execute('insert into currency (id,from_currency,to_currency,date,time,currency,created_at) values (%s,%s,%s,%s,%s,%s,%s)', [uid,fromCurrency,toCurrency,dates,times,currency,created_at])
			conn.commit()
			time.sleep(0.5)
	
	cur.close()
	conn.close()
getCurrency(['USD','EUR','CAD','GBP','HKD'])
# req = urllib.request.Request(url)

# req.add_header("apikey", apikey)

# resp = urllib.request.urlopen(req)
# content = resp.read()
# if(content):
#     a = json.loads(bytes.decode(content))
#     print(len(a['retData']))
#     getCurrency(a['retData'])
